<template>
  <div class="editor">
    <div style="border: 1px solid #ccc">
      <Toolbar
        style="border-bottom: 1px solid #ccc"
        :editor="editorRef"
        :defaultConfig="toolbarConfig"
        :mode="mode"
      />
      <Editor
        style="height: 800px; overflow-y: hidden"
        v-model="valueHtml"
        :defaultConfig="editorConfig"
        :mode="mode"
        @onCreated="handleCreated"
      />
    </div>
    <div class="foot">
      <el-button @click="submit" type="primary"> 提交 </el-button>
    </div>
  </div>
</template>
<script lang="ts" setup>
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { onBeforeUnmount, ref, shallowRef, onMounted, nextTick } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { postUploadImageApi } from '@/service/api'
import { isCode } from '@/utils/iscode'
import { useRoute } from 'vue-router'
import useEditorStore from '@/stores/main/editor/editor'
//  编辑器实例，必须用 shallowRef
const editorRef = shallowRef()
// 内容 HTML
const valueHtml = ref('')

const mode = 'default' // 或 'simple'

const emits = defineEmits(['submit'])

const route = useRoute()

const editorStore = useEditorStore()

onMounted(() => {
  if (route.query.id) {
    nextTick(() => {
      valueHtml.value = editorStore.editor.content
    })
  }
})

const toolbarConfig = {}
const editorConfig = { placeholder: '请输入内容...', MENU_CONF: {} }

//自定义上传图片
editorConfig.MENU_CONF['uploadImage'] = {
  // 自定义插入图片
  async customUpload(file, insertFn) {
    let data = new FormData()
    data.append('file', file) //file为上传文件返回的所有file
    let res = await postUploadImageApi(data)
    if (isCode(res)) {
      insertFn(res.result.url, file.name, res.result.url)
    }
  }
}

//自定义上传视频
editorConfig.MENU_CONF['uploadVideo'] = {
  // 自定义插入图片
  async customUpload(file, insertFn) {
    let data = new FormData()
    data.append('file', file) //file为上传文件返回的所有file
    let res = await postUploadImageApi(data)
    if (isCode(res)) {
      insertFn(res.result.url, file.name, res.result.url)
    }
  }
}

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

const handleCreated = (editor) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}

const submit = () => {
  emits('submit', valueHtml.value)
}
</script>
<style lang="less" scoped>
.editor {
  .foot {
    width: 100%;
    text-align: center;
    margin-top: 30px;
  }
}
</style>
